<template>
  <div class="nil-search">
    <el-form :inline="true" :model="formInline">
      <el-form-item
          :label="item.label || '未定义'"
          v-for="(item, index) in form"
          :key="index"
      >
        <el-select
            v-if="item.type === 'select'"
            v-model="formInline[item.model]"
            :placeholder="item.placeholder ?? `请选择${item.label}`"
        >
          <el-option
              v-for="(it, index) in item.options"
              :key="index"
              :label="it.label"
              :value="it.value"
          ></el-option>
        </el-select>
        <el-date-picker
            v-else-if="item.type === 'date'"
            v-model="formInline[item.model]"
            :placeholder="item.placeholder ?? `请选择${item.label}`"
            type="date"
        ></el-date-picker>

        <el-input
            v-else
            v-model="formInline[item.model]"
            :placeholder="item.placeholder ?? `请输入${item.label}`"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button :type="searchType" @click="onSubmit">{{ searchText }}</el-button>
        <el-button :type="cancelType" @click="onCancel">{{ cancelText }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import {defineComponent, onBeforeMount, reactive} from "vue";
import { searchProps} from "./extra";

const IS_INIT = {
  TRUE: true,
  FALSE: false
}

export default defineComponent({
  name: "NilSearch",
  props: searchProps,
  emits: ["search"],
  setup(props, { emit }) {
    // 定义表单的内容
    const formInline = reactive({});
    // 根据 prop 初始化 formInline
    const reData = (isInit) => {
      if (props.form && props.form.length > 0) {
        props.form.forEach((it) => {
          formInline[it.model] = isInit ? it.default ?? "" : "";
        });
      } else {
        console.warn("nil-search 组件 prop 项 form 必须传入");
      }
    };

    onBeforeMount(() => {
      reData(IS_INIT.TRUE);
    })

    const onSubmit = () => {
      emit("search", formInline);
    };

    const onCancel = () => {
      reData(IS_INIT.FALSE);
      emit("search", formInline);
    };

    return {
      formInline,
      onSubmit,
      onCancel
    };
  },
});
</script>

<style scoped></style>
